#include "ServerInfoRes.h"
#include "localIp.h"
#include "deviceCode.h"
#include "localVersion.h"
#include "roomInfo.h"
#include "jsonUtils.h"
#include "stringUtils.h"

extern uint16_t udp_port;

ServerInfoRes::ServerInfoRes() : OperatorResponse(true)
{
	ip = LocalIp::ip();
	port = udp_port;
	version = LocalVersion::exeVersion();
	code = DeviceCode::inst().getDeviceCode();
}

JsonDoc& ServerInfoRes::jsonSerialize()
{
	JsonDoc& doc = OperatorResponse::jsonSerialize();
	JsonValue obj(rapidjson::kObjectType);
	if (!ip.empty()) {
		JsonUtils::addString(obj, L"ip", ip, doc.GetAllocator());
	}
	obj.AddMember(L"port", port, doc.GetAllocator());
	JsonUtils::addString(obj, L"room", RoomInfo::inst().roomName(), doc.GetAllocator());
	JsonUtils::addString(obj, L"version", version, doc.GetAllocator());
	JsonUtils::addString(obj, L"code", code, doc.GetAllocator());

	doc.AddMember(L"data",obj,doc.GetAllocator());
	return doc;
}

JsonDoc& ServerInfoRes::jsonDeserialize(const String& json)
{
	JsonDoc& doc = OperatorResponse::jsonDeserialize(json);
	JsonValue::ConstMemberIterator it = doc.FindMember(L"data");
	if (it != doc.MemberEnd() && it->value.IsObject()) {
		rapidjson::GenericObject<true,JsonValue> obj = it->value.GetObject();
		JsonValue::ConstMemberIterator it = obj.FindMember(L"ip");
		if (it != obj.MemberEnd() && it->value.IsString()) {
			ip = it->value.GetString();
		}
		it = obj.FindMember(L"port");
		if (it != obj.MemberEnd() && it->value.IsNumber()) {
			port = it->value.GetInt();
		}
		it = obj.FindMember(L"room");
		if (it != obj.MemberEnd() && it->value.IsString())
		{
			room = it->value.GetString();
		}
		it = obj.FindMember(L"version");
		if (it != obj.MemberEnd() && it->value.IsString())
		{
			version = it->value.GetString();
		}
		it = obj.FindMember(L"code");
		if (it != obj.MemberEnd() && it->value.IsString())
		{
			code = it->value.GetString();
		}
	}
	return doc;
}
